package com.zzzy.cont.controller.mycon;


import com.zhuozhengsoft.pageoffice.DocumentOpenType;
import com.zhuozhengsoft.pageoffice.FileMakerCtrl;
import com.zhuozhengsoft.pageoffice.FileSaver;
import com.zhuozhengsoft.pageoffice.word.WordDocumentWriter;
import com.zzzy.common.util.AssertUtil;
import com.zzzy.common.util.FileUtil;
import com.zzzy.common.vo.AjaxResult;
import com.zzzy.cont.service.mycon.MyConAuditService;
import com.zzzy.cont.vo.contract.my.ConBasicInfoRes;
import com.zzzy.cont.vo.contract.my.ConInfoRes;
import com.zzzy.framework.config.PageofficeConfig;
import io.swagger.v3.oas.annotations.Operation;
import io.swagger.v3.oas.annotations.Parameter;
import io.swagger.v3.oas.annotations.tags.Tag;
import org.apache.commons.lang3.StringUtils;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.validation.annotation.Validated;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.validation.constraints.NotNull;
import java.io.IOException;
import java.util.Objects;

@Tag(name = "我的合同-审核中", description = "con111")
@Validated
@RestController
@RequestMapping("/con/my")
public class MyConAuditController {

    @Resource
    private MyConAuditService myConAuditService;
    @Resource
    private PageofficeConfig pageofficeConfig;

    @PutMapping("/applyAudit")
    @Operation(summary = "申请审核")
    @Parameter(name = "id", description = "合同ID", required = true)
    @Parameter(name = "userId", description = "用户ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public AjaxResult applyAudit(@NotNull(message = "合同ID不能为空") Long id, @NotNull(message = "用户ID不能为空") Long userId) {
        myConAuditService.applyAudit(id, userId);
        return AjaxResult.success();
    }

    @PostMapping(value = "/updateAuditFile")
    @Operation(summary = "保存审核中文件")
    @Parameter(name = "id", description = "合同ID", required = true)
    @Parameter(name = "revisionCount", description = "Word中的修订痕迹数量", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public void updateAuditFile(@NotNull(message = "合同ID不能为空") @RequestParam("id") Long id, Integer revisionCount
            , HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        revisionCount = revisionCount == null ? 0 : revisionCount;
        myConAuditService.updateWord(id, fs.getFileBytes(), revisionCount);
        fs.setCustomSaveResult("ok");
        fs.close();
    }

    @PutMapping("/auditComplete/{id}")
    @Operation(summary = "审核完毕进入签订")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public AjaxResult auditComplete(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id) {
        myConAuditService.auditComplete(id);
        return AjaxResult.success();
    }

    @GetMapping("/isNeedTransPdf/{id}")
    @Operation(summary = "是否需要转换pdf后进入审核")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public AjaxResult isNeedTransPdf(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id) {
        ConInfoRes conInfoRes = myConAuditService.getConInfo(id);
        return AjaxResult.success(Objects.isNull(conInfoRes.getPdfFileBlob()));
    }

    @PostMapping("/wordToPdf/{id}")
    @Operation(summary = "word转换为PDF")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public void wordToPdf(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id
            , HttpServletRequest request, HttpServletResponse response) throws IOException {
        ConBasicInfoRes conBasicInfo = myConAuditService.getConBasicInfo(id);
        AssertUtil.isEquals(0, conBasicInfo.getRevisionCount(), "仍有修订痕迹无法保存");
        String openFileUrl = "/con/my/getConFileStream/" + id;
        FileMakerCtrl fmCtrl = new FileMakerCtrl(request);
        if (StringUtils.isNotBlank(pageofficeConfig.getWaterMark())) {
            WordDocumentWriter doc = new WordDocumentWriter();
            doc.getWaterMark().setText(pageofficeConfig.getWaterMark());
            fmCtrl.setWriter(doc);
        }
        fmCtrl.fillDocumentAsPDF(openFileUrl, DocumentOpenType.Word, conBasicInfo.getName()+ ".pdf");
        response.getOutputStream().print(fmCtrl.getHtml());
    }

    @PostMapping(value = "/auditCompleteWithSavePdf/{id}")
    @Operation(summary = "审核完毕并保存pdf")
    @Parameter(name = "id", description = "合同ID", required = true)
    @PreAuthorize("@pvs.hasPermission('con:my:update')")
    public void auditWithSavePdf(@NotNull(message = "合同ID不能为空") @PathVariable("id") Long id,
                                 HttpServletRequest request, HttpServletResponse response) {
        FileSaver fs = new FileSaver(request, response);
        byte[] byteArray = FileUtil.toByteArray(fs.getFileStream());
        myConAuditService.auditWithSavePdf(id, byteArray);
        fs.setCustomSaveResult("ok");
        fs.close();
    }
}
